package org.fxd.zweixin.busi_wx.user.api;

import java.util.ArrayList;
import java.util.List;

import org.fxd.zweixin.busi_system.set.service.SettingService;
import org.fxd.zweixin.busi_wx.user.domain.wx_user;
import org.fxd.zweixin.busi_wx.user.service.WxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.tmsps.ne4spring.base.BaseAction;
import org.tmsps.ne4spring.utils.ChkUtil;
import org.tmsps.ne4spring.utils.JsonUtil;
import org.tmsps.ne4spring.utils.WebUtil;
import org.tmsps.ne4spring.utils.wrapper.WrapMapper;
import org.tmsps.ne4spring.utils.wrapper.Wrapper;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.SnsApi;
import com.jfinal.weixin.sdk.api.UserApi;

import net.dreamlu.weixin.annotation.WxApi;

@WxApi("/weixin/api/user")
public class WeixinUserApiController extends BaseAction {

	@Autowired
	private WxUserService wxUserService;
	@Autowired
	private SettingService settingService;

	// 从前端获取用户信息
	@GetMapping("/getUserCount")
	@ResponseBody
	public Wrapper<JSONObject> getUserCount() {
		JSONObject json = new JSONObject();
		long count1 = wxUserService.getCountWxUser();
		long count2 = ChkUtil.getInteger(settingService.getVal("count2"));
		json.put("count1", count1);
		json.put("count2", count2);
		return WrapMapper.ok(json);
	}

	// 从前端获取用户信息
	@GetMapping("/getUserInfo")
	@ResponseBody
	public Wrapper<wx_user> getUserInfo(String code) {
		ApiConfig ac = ApiConfigKit.getApiConfig();
		SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(ac.getAppId(), ac.getAppSecret(), code);
		if (snsAccessToken.isAvailable()) {
			ApiResult userInfo = SnsApi.getUserInfo(snsAccessToken.getAccessToken(), snsAccessToken.getOpenid());
			JSONObject userInfoJson = JsonUtil.jsonStrToJsonObject(userInfo.getJson());
			wx_user user = wxUserService.subscribe(userInfoJson);
			return WrapMapper.ok(user);
		}
		return WrapMapper.error();
	}

	// 从后端获取用户信息
	@GetMapping("/getUserInfoBack")
	@ResponseBody
	public Wrapper<JSONObject> getUserInfoBack(String openid) {
		ApiResult userInfo = UserApi.getUserInfo(openid);
		JSONObject userInfoJson = JsonUtil.jsonStrToJsonObject(userInfo.getJson());
		return WrapMapper.ok(userInfoJson);
	}

	@GetMapping("/user_list")
	@ResponseBody
	public String user_list() {
		ApiResult apiResult = UserApi.getFollows();
		JSONObject json = JsonUtil.jsonStrToJsonObject(apiResult.getJson());
		JSONArray openIdArray = json.getJSONObject("data").getJSONArray("openid");

		List<String> openIdList = new ArrayList<>();
		for (int i = 0; i < openIdArray.size(); i++) {
			if ((i + 1) % 100 == 0) {
				// 攒够100人加载一次
				loadWxUserInfo(openIdList);
			}
			openIdList.add(openIdArray.getString(i));
		}
		// 最后加载剩余用户
		if (openIdList.size() > 0) {
			loadWxUserInfo(openIdList);
		}

		return apiResult.getJson();
	}

	private void loadWxUserInfo(List<String> openIdList) {
		ApiResult batchGetUserInfoResult = UserApi.batchGetUserInfo(openIdList);
		JSONObject json2 = JsonUtil.jsonStrToJsonObject(batchGetUserInfoResult.getJson());
		JSONArray userArray = json2.getJSONArray("user_info_list");
		openIdList.clear();
		for (int j = 0; j < userArray.size(); j++) {
			JSONObject userJson = userArray.getJSONObject(j);
			wx_user wxUser = JSON.toJavaObject(userJson, wx_user.class);
			bs.saveObj(wxUser);
		}
	}

	// 从前端获取用户信息
	@PostMapping("/saveInfo")
	@ResponseBody
	public Wrapper<String> saveInfo(String sms_code, String openid, String sys_mobile, String sys_name,
			String sys_code) {
		String sms_code_sn = (String) WebUtil.getSession().getAttribute("sms_code");
		if (ChkUtil.isNull(sms_code) || !sms_code.equals(sms_code_sn)) {
			return WrapMapper.error("短信验证码有误!");
		}
		wx_user user = wxUserService.findUserByOpenid(openid);
		if (user == null) {
			return WrapMapper.error("系统异常,请稍后再试.");
		}
		if (!ChkUtil.isMobile(sys_mobile)) {
			return WrapMapper.error("请输入正确的手机号.");
		}
		user.setSys_mobile(sys_mobile);
		user.setSys_name(sys_name);
		user.setSys_code(sys_code);
		bs.updateObj(user);
		return WrapMapper.ok("保存成功.");

	}

}
